package com.xh.bussiness.thirdapi.xiaoguanjia.service.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.permission.bean.request.UserRequest;
import com.xh.bussiness.permission.model.School;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.bean.dto.StudentBean;
import com.xh.bussiness.system.model.Student;
import com.xh.bussiness.system.service.ISchoolService;
import com.xh.bussiness.system.service.IStudentService;
import com.xh.bussiness.log.model.AsynThirdLog;
import com.xh.bussiness.log.service.IAsynThirdLogService;
import com.xh.bussiness.thirdapi.xiaoguanjia.bean.request.XgjBaseRequest;
import com.xh.bussiness.thirdapi.xiaoguanjia.constant.XiaoGuanJiaConstant;
import com.xh.bussiness.thirdapi.xiaoguanjia.model.*;
import com.xh.bussiness.thirdapi.xiaoguanjia.service.IXiaoGuanJiaService;
import com.xh.bussiness.tms.model.Class;
import com.xh.bussiness.tms.model.ClassStudent;
import com.xh.bussiness.tms.service.IClassManageService;
import com.xh.bussiness.tms.service.IClassStudentService;
import com.xh.core.util.CacheUtils;
import com.xh.core.util.DateUtils;
import com.xh.core.util.StringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;

@Service
public class XiaoGuanJiaServiceImpl implements IXiaoGuanJiaService {

//    @Value("${xgj.appid}")
    private String appId;
//    @Value("${xgj.secret}")
    private String secret;
//    @Value("${xgj.urlPrefix}")
    private String urlPrefix;

    @Autowired
    private IAsynThirdLogService asynThirdLogService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private IUserService userService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IClassManageService classManageService;
    @Autowired
    private IClassStudentService classStudentService;
    @Autowired
    private ISchoolService schoolService;

    public String getToken() {
//        if (CacheUtils.get("xgjToken") != null) {
//            return (String) CacheUtils.get("xgjToken");
//        }
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("appid=" + appId);
        joiner.add("secret=" + secret);
        String requestUrl = XiaoGuanJiaConstant.API_GET_TOKEN + joiner.toString();
        String resposeStr = doRemotRequest(requestUrl);
        if (StringUtils.isNotEmpty(resposeStr)) {
            XgjToken xgjToken = JSON.parseObject(resposeStr, XgjToken.class);
            String token = xgjToken.getAccess_token();
            // 设置缓存
            CacheUtils.set("xgjToken", token, xgjToken.getExpires_in() * 800);
            return token;
        }
        return null;
    }

    @Override
    public int importTeacher(XgjBaseRequest bean) throws Exception {
        String token = getToken();
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("access_token=" + token);
        joiner.add("updatetime=" + bean.getUpdatetime());
        joiner.add("size=100");
        int pageNo = 0;
        boolean hasMore = true;
        int lastSize = 0;
        do {
            pageNo++;
            String requestUrl = XiaoGuanJiaConstant.API_GET_USER + joiner.toString() + "&offset=" + pageNo;
            String resposeStr = doRemotRequest(requestUrl);
            if (StringUtils.isNotEmpty(resposeStr)) {
                Map resMap = JSON.parseObject(resposeStr, Map.class);
                int errcode = MapUtils.getIntValue(resMap, "errcode");
                if (errcode == 0) {
                    //当前分页条件下，是否还有下一页更多数据（0否，1是）
                    hasMore = MapUtils.getIntValue(resMap, "has_more") > 0;
                    String data = MapUtils.getString(resMap, "data");
                    if (null != data) {
                        List<XgjEmployee> xgjEmployees = JSON.parseArray(data, XgjEmployee.class);
                        asyncUser(xgjEmployees);
                        if (!hasMore) {
                            lastSize = xgjEmployees.size();
                        }
                    }

                } else {
                    throw new Exception(MapUtils.getString(resMap, "errmsg"));
                }
            }

        } while (hasMore);

        Integer total = pageNo * 100 + lastSize;
        AsynThirdLog log = new AsynThirdLog();
        log.setImportName("校管家教师导入");
        log.setImportTotal(total);
        asynThirdLogService.insert(log);
        return total;
    }

    private void asyncUser(List<XgjEmployee> xgjEmployees) {
        for (int i = 0; i < xgjEmployees.size(); i++) {
            XgjEmployee xgjEmployee = xgjEmployees.get(i);
            // 删除和禁用的数据我们不要，只保留有效数据
            if (xgjEmployee.getUser_status() != 1) {
                continue;
            }
            String mobile = xgjEmployee.getSmstel();
            // 我们系统里的id是32位的UUID,校管家的是36位
            String employee_id = xgjEmployee.getEmployee_id().replace("-", "");
            User exists = userService.getById(employee_id);
            if (exists != null) {
                User user = new User();
                user.setId(exists.getId());
                user.setStatus(0);
                user.setUsername(xgjEmployee.getName());
                user.setMobile(mobile);
                userService.update(user);
            } else {
                UserRequest request = new UserRequest();
                request.setId(employee_id);
                request.setMobile(mobile);
                request.setNickname(xgjEmployee.getName());
                request.setUsername(xgjEmployee.getName());
                request.setStatus(0);
                request.setIsFront(1);
                request.setIsAdmin(1);
                request.setSource(1);
                request.setThirdId(xgjEmployee.getEmployee_id());
                // 默认 “系统默认” 教师分组
                request.setGroupIds(Collections.singletonList("572feae25a6a40ba8d044d000cc2705c"));
                // 默认 “系统默认” 角色
                request.setRoleIds(Collections.singletonList("90056f4a83064daabedcc4dff7b22f78"));
                userService.addUser(request);
            }
        }
    }

    @Override
    public int importStudent(XgjBaseRequest bean) throws Exception {
        String token = getToken();
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("access_token=" + token);
        joiner.add("updatetime=" + bean.getUpdatetime());
        joiner.add("size=100");
        int pageNo = 0;
        boolean hasMore = true;
        do {
            pageNo++;
            String requestUrl = XiaoGuanJiaConstant.API_GET_STUDENT_BATCH + joiner.toString() + "&offset=" + pageNo;
            String resposeStr = doRemotRequest(requestUrl);
            if (StringUtils.isNotEmpty(resposeStr)) {
                Map resMap = JSON.parseObject(resposeStr, Map.class);
                int errcode = MapUtils.getIntValue(resMap, "errcode");
                if (errcode == 0) {
                    //当前分页条件下，是否还有下一页更多数据（0否，1是）
                    hasMore = MapUtils.getIntValue(resMap, "has_more") > 0;
                    String data = MapUtils.getString(resMap, "data");
                    if (null != data) {
                        List<XgjStudent> xgjStudents = JSON.parseArray(data, XgjStudent.class);
                        asyncStudent(xgjStudents);
                    }
                } else {
                    throw new Exception(MapUtils.getString(resMap, "errmsg"));
                }
            }

        } while (hasMore);

        return 0;
    }

    private void asyncStudent(List<XgjStudent> xgjStudents) throws ParseException {
        Date now = new Date();
        for (int i = 0; i < xgjStudents.size(); i++) {
            XgjStudent xgjStudent = xgjStudents.get(i);
            // 	状态（-1已删除，0试听，1在读，3休学，99已退校）
            if (xgjStudent.getStatus() == 1) {
                StudentBean student = new StudentBean();
                student.setId(xgjStudent.getStudent_id().replace("-", ""));
                student.setSex(xgjStudent.getSex() == 2 ? 0 : 1);
                student.setName(xgjStudent.getName());
                // 获取学生的登录手机号：1、学生自己的手机号  2、母亲的手机号  3、父亲的手机号
                String phone = StringUtils.isEmpty(xgjStudent.getSmstel()) ? StringUtils.isEmpty(xgjStudent.getMother_tel()) ? StringUtils.isEmpty(xgjStudent.getFather_tel()) ? null : xgjStudent.getFather_tel() : xgjStudent.getMother_tel() : xgjStudent.getSmstel();
                student.setMotherPhone(phone == null ? null : phone.length() > 11 ? null : phone);
                student.setFatherPhone(xgjStudent.getFather_tel() == null ? null : xgjStudent.getFather_tel().length() > 11 ? null : xgjStudent.getFather_tel());
                student.setBirthday(xgjStudent.getBirthday());
                student.setSource(1);
                student.setThirdId(xgjStudent.getStudent_id());
                student.setStatus(1);
                studentService.saveOrUpadte(student);
            }
        }
    }

    @Override
    public int importClass(XgjBaseRequest bean, boolean asyncTeacher, boolean asyncStudent) throws Exception {
        String token = getToken();
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("access_token=" + token);
        joiner.add("updatetime=" + bean.getUpdatetime());
        joiner.add("size=100");
        int pageNo = 0;
        boolean hasMore = true;
        do {
            pageNo++;
            String requestUrl = XiaoGuanJiaConstant.API_GET_CLASS_BATCH + joiner.toString() + "&offset=" + pageNo;
            String resposeStr = doRemotRequest(requestUrl);
            if (StringUtils.isNotEmpty(resposeStr)) {
                Map resMap = JSON.parseObject(resposeStr, Map.class);
                int errcode = MapUtils.getIntValue(resMap, "errcode");
                if (errcode == 0) {
                    //当前分页条件下，是否还有下一页更多数据（0否，1是）
                    hasMore = MapUtils.getIntValue(resMap, "has_more") > 0;
                    String data = MapUtils.getString(resMap, "data");
                    if (null != data) {
                        List<XgjClass> xgjClasses = JSON.parseArray(data, XgjClass.class);
                        asyncClass(xgjClasses, asyncTeacher, asyncStudent);
                    }
                } else {
                    throw new Exception(MapUtils.getString(resMap, "errmsg"));
                }
            }

        } while (hasMore);
        return 0;
    }

    @Override
    public int importStudentClass(XgjBaseRequest bean) throws Exception {
        String token = getToken();
        List<Student> students = studentService.queryAll();
        for (Student student : students) {
            StringJoiner joiner = new StringJoiner("&", "?", "");
            joiner.add("access_token=" + token);
            joiner.add("student_id=" + student.getThirdId());
            boolean hasMore = true;
            String requestUrl = XiaoGuanJiaConstant.API_GET_STUDENT_CLASS + joiner.toString();
            String resposeStr = doRemotRequest(requestUrl);
            if (StringUtils.isNotEmpty(resposeStr)) {
                Map resMap = JSON.parseObject(resposeStr, Map.class);
                int errcode = MapUtils.getIntValue(resMap, "errcode");
                if (errcode == 0) {
                    //当前分页条件下，是否还有下一页更多数据（0否，1是）
                    hasMore = MapUtils.getIntValue(resMap, "has_more") > 0;
                    String data = MapUtils.getString(resMap, "data");
                    if (null != data) {
                        List<XgjStudentClass> xgjStudentClasses = JSON.parseArray(data, XgjStudentClass.class);
                        if (CollectionUtils.isEmpty(xgjStudentClasses)) {
                            continue;
                        }
                        asyncStudentClass(student.getId(), xgjStudentClasses);
                    }
                } else {
                    throw new Exception(MapUtils.getString(resMap, "errmsg"));
                }
            }
        }
        return 0;
    }

    private void asyncStudentClass(String studentId, List<XgjStudentClass> xgjStudentClasses) {
        for (XgjStudentClass xgjStudentClass : xgjStudentClasses) {
            ClassStudent classStudent = new ClassStudent();
            classStudent.setClassId(xgjStudentClass.getClass_id().replace("-", ""));
            classStudent.setStudentId(studentId);
            classStudentService.insert(classStudent);
        }
    }

    @Override
    public int importClassStudents(XgjBaseRequest bean) throws Exception {
        String token = getToken();
        List<Class> classes = classManageService.queryAll();
        for (Class cls : classes) {
            asyncClassStudents(cls);
        }
        return 0;
    }

    @Override
    public int importSchool(XgjBaseRequest bean) throws Exception {
        String token = getToken();
        if (null == token) {
            token = getToken();
        }
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("access_token=" + token);
        joiner.add("updatetime=" + bean.getUpdatetime());
        joiner.add("size=100");
        int pageNo = 0;
        boolean hasMore = true;
        do {
            pageNo++;
            String requestUrl = XiaoGuanJiaConstant.API_GET_SCHOOL + joiner.toString() + "&offset=" + pageNo;
            String resposeStr = doRemotRequest(requestUrl);
            if (StringUtils.isNotEmpty(resposeStr)) {
                Map resMap = JSON.parseObject(resposeStr, Map.class);
                int errcode = MapUtils.getIntValue(resMap, "errcode");
                if (errcode == 0) {
                    //当前分页条件下，是否还有下一页更多数据（0否，1是）
                    hasMore = MapUtils.getIntValue(resMap, "has_more") > 0;
                    String data = MapUtils.getString(resMap, "data");
                    if (null != data) {
                        List<XgjSchool> xgjSchools = JSON.parseArray(data, XgjSchool.class);
                        if (CollectionUtils.isEmpty(xgjSchools)) {
                            continue;
                        }
                        asyncSchool(xgjSchools);
                    }
                } else {
                    throw new Exception(MapUtils.getString(resMap, "errmsg"));
                }
            }

        } while (hasMore);

        return 0;
    }

    @Override
    public int syncClassStudentsById(String id) throws ParseException {
        Class cls = classManageService.getById(id);
        asyncClassStudents(cls);
        return 0;
    }

    private void asyncSchool(List<XgjSchool> xgjSchools) {
        for (XgjSchool xgjSchool : xgjSchools) {
            // 只同步校区，只同步有效数据
            if (!xgjSchool.getIscampus() || xgjSchool.getStatus() != 1) {
                continue;
            }
            School school = new School();
            school.setId(xgjSchool.getDept_id().replace("-", ""));
            school.setSchoolName(xgjSchool.getName());
            school.setStatus(xgjSchool.getStatus());
            school.setThirdId(xgjSchool.getDept_id());
            school.setSchoolAddress(xgjSchool.getAddress());
            schoolService.saveOrUpdate(school);
        }
    }

    @Override
    public int importClassTeacher(XgjBaseRequest bean) throws Exception {
        List<Class> classes = classManageService.queryAll();
        for (Class cls : classes) {
            asyncClassTeacher(cls);
        }
        return 0;
    }

    private void asyncClassTeacher(Class cls) throws Exception {
        String token = getToken();
        if (null == token) {
            token = getToken();
        }
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("access_token=" + token);
        joiner.add("class_id=" + cls.getThirdId());
        boolean hasMore = true;
        String requestUrl = XiaoGuanJiaConstant.API_GET_CLASS_TEACHER + joiner.toString();
        String resposeStr = doRemotRequest(requestUrl);
        if (StringUtils.isNotEmpty(resposeStr)) {
            Map resMap = JSON.parseObject(resposeStr, Map.class);
            int errcode = MapUtils.getIntValue(resMap, "errcode");
            if (errcode == 0) {
                String data = MapUtils.getString(resMap, "data");
                if (null != data) {
                    List<XgjClassTeacher> xgjClassTeachers = JSON.parseArray(data, XgjClassTeacher.class);
                    if (CollectionUtils.isEmpty(xgjClassTeachers)) {
                        return;
                    }
                    updateClassTeacher(cls, xgjClassTeachers);
                }
            } else {
                throw new Exception(MapUtils.getString(resMap, "errmsg"));
            }
        }
    }

    private void updateClassTeacher(Class cls, List<XgjClassTeacher> xgjClassTeachers) {
        String teacherId = null;
        for (XgjClassTeacher xgjClassTeacher : xgjClassTeachers) {
            // 主教
            if (xgjClassTeacher.getRole() == 1) {
                teacherId = xgjClassTeacher.getEmployee_id().replace("-", "");
                break;
            }
        }
        if (StringUtils.isNotEmpty(teacherId)) {
            cls.setTeacherId(teacherId);
            classManageService.update(cls);
        }
    }

    private void asyncClass(List<XgjClass> xgjClasses, boolean asyncTeacher, boolean asyncStudent) throws Exception {
        if (CollectionUtils.isEmpty(xgjClasses)) {
            return;
        }
        for (XgjClass xgjClass : xgjClasses) {
            // 只保留有效数据，无效数据不同步
            if (xgjClass.getStatus() == 0) {
                continue;
            }
            Class cls = new Class();
            String id = xgjClass.getClass_id().replace("-", "");
            cls.setId(id);
            cls.setTitle(xgjClass.getName());
            cls.setStatus(1);
            cls.setTeacherId(xgjClass.getHeadmaster_id().replace("-", ""));
            cls.setThirdId(xgjClass.getClass_id());
            cls.setSource("1");
            classManageService.saveOrUpdate(cls);
            if (asyncTeacher) {
                asyncClassTeacher(cls);
            }
            if (asyncStudent) {
                asyncClassStudents(cls);
            }
        }
    }

    private void asyncClassStudents(Class cls) throws ParseException {
        String token = getToken();
        StringJoiner joiner = new StringJoiner("&", "?", "");
        joiner.add("access_token=" + token);
        joiner.add("class_id=" + cls.getThirdId());
        String requestUrl = XiaoGuanJiaConstant.API_GET_CLASS_STUDENTS + joiner.toString();
        String resposeStr = doRemotRequest(requestUrl);
        if (StringUtils.isNotEmpty(resposeStr)) {
            Map resMap = JSON.parseObject(resposeStr, Map.class);
            int errcode = MapUtils.getIntValue(resMap, "errcode");
            if (errcode == 0) {
                //当前分页条件下，是否还有下一页更多数据（0否，1是）
                String data = MapUtils.getString(resMap, "data");
                if (null != data) {
                    List<XgjClassStudent> xgjClassStudents = JSON.parseArray(data, XgjClassStudent.class);
                    if (CollectionUtils.isEmpty(xgjClassStudents)) {
                        return;
                    }
                    Date now = new Date();
                    for (XgjClassStudent xgjClassStudent : xgjClassStudents) {
                        // 状态（0从班级中移出，1进入班级中，2停课，3退出班级，-1删除） 只保留有效数据
                        Date indate = DateUtils.parseDate(xgjClassStudent.getIndate(), "yyyyMMddHHmmss");
                        Date outdate = DateUtils.parseDate(xgjClassStudent.getOutdate(), "yyyyMMddHHmmss");
                        if (xgjClassStudent.getStatus() != 1 || !(now.after(indate) && now.before(outdate))) {
//                            ClassStudent bean = new ClassStudent();
//                            bean.setClassId(classId);
//                            bean.setStudentId(xgjClassStudent.getStudent_id().replace("-", ""));
//                            classStudentService.deleteStudentOrClassByClassIdOrStuId(bean);
                            continue;
                        }
                        ClassStudent classStudent = new ClassStudent();
                        classStudent.setClassId(cls.getId());
                        classStudent.setStudentId(xgjClassStudent.getStudent_id().replace("-", ""));
                        classStudentService.insert(classStudent);
                    }
                }
            }
        }
    }

    public String doRemotRequest(String requestUrl) {
        String uri = urlPrefix + requestUrl;
        return restTemplate.getForObject(uri, String.class);
    }
}
